using UniversalAdminSystem.Domian.PermissionManagement.Exceptions;
using UniversalAdminSystem.Domian.PermissionManagement.ValueObjects;

namespace UniversalAdminSystem.Domian.PermissionManagement.Services;

/// <summary>
/// 资源-操作组合校验器
/// 职责：验证资源与操作类型的组合是否合法
/// </summary>
public class ResourceActionValidator
{
    private static readonly object _lock = new object();
    private static Dictionary<PermissionAction, HashSet<string>> _validResources = new();

    /// <summary>
    /// 加载权限规则配置
    /// </summary>
    public static void LoadRules(Dictionary<PermissionAction, HashSet<string>> rules)
    {
        lock (_lock)
        {
            _validResources = rules.ToDictionary(kv => kv.Key, kv => kv.Value.ToHashSet());
        }
    }

    /// <summary>
    /// 获取当前配置的规则
    /// </summary>
    public static Dictionary<PermissionAction, HashSet<string>> GetCurrentRules()
    {
        lock (_lock)
        {
            return _validResources.ToDictionary(kv => kv.Key, kv => kv.Value.ToHashSet());
        }
    }

    /// <summary>
    /// 验证资源-操作组合有效性
    /// </summary>
    public static bool IsValidCombination(string resource, int actionValue, out PermissionResource permSource, out PermissionAction permAction)
    {
        lock (_lock)
        {
            permSource = PermissionResource.Create(resource);
            var resourceModule = permSource.GetModule();
            if (!Enum.TryParse(actionValue.ToString(), out PermissionAction validAction))
                throw new PermissionDomainException("无效的操作类型值");
            permAction = validAction;
            return _validResources.TryGetValue(validAction, out var validModules) && validModules.Contains(resourceModule);
        }
    }
}